//
//  GFTextRestrict.m
//  qmtest
//
//  Created by 岳云石 on 2017/3/24.
//  Copyright © 2017年 岳云石. All rights reserved.
//

#import "GFTextRestrict.h"

@interface GFNumberTextRestrict : GFTextRestrict

@end

//@interface GFDecimalTextRestrict : GFTextRestrict
//
//@end

@interface GFTextRestrict ()

@property (nonatomic, readwrite) GFRestrictType restrictType;

@end


@implementation GFTextRestrict

+ (instancetype)textRestrictWithRestrictType: (GFRestrictType)restrictType
{
    GFTextRestrict * textRestrict;
    switch (restrictType) {
        case GFRestrictTypeOnlyNumber:
            textRestrict = [[GFNumberTextRestrict alloc] init];
            break;
            
//        case GFRestrictTypeOnlyDecimal:
//            textRestrict = [[GFDecimalTextRestrict alloc] init];
//            break;
            
        default:
            break;
    }
    textRestrict.maxLength = NSUIntegerMax;
    textRestrict.restrictType = restrictType;
    return textRestrict;
}

// 输入中验证
- (void)textDidChanged: (UITextField *)textField
{
  //应该在子类中实现 但是不实现会报警告
}

- (NSString *)restrictMaxLength: (NSString *)text
{
    if (text.length > _maxLength) {
        text = [text substringToIndex: self.maxLength];
    }
    return text;
}

- (NSString *)FilterString:(NSString *)targetString Filter:(GFStringFilter)filter{
    NSMutableString * modifyString = targetString.mutableCopy;
    for (int idx = 0; idx <modifyString.length;) {
        NSString *substring = [modifyString substringWithRange:NSMakeRange(idx, 1)];
        if (filter(substring)) {
            idx++;
        }else{
            [modifyString deleteCharactersInRange: NSMakeRange(idx, 1)];
        }
    }
    
    return modifyString;
}

- (BOOL)MatchStringFormat:(NSString *)targetString  MatchFormat:(NSString *)matchFormat{
    NSPredicate * predicate = [NSPredicate predicateWithFormat: @"SELF MATCHES %@", matchFormat];
    return [predicate evaluateWithObject: targetString];
}

@end

@implementation GFNumberTextRestrict

- (void)textDidChanged:(UITextField *)textField{
    NSLog(@"-------textField.text = %@",textField.text);
    NSString * filterText = [self FilterString:textField.text Filter:^BOOL(NSString *targetString) {
        NSLog(@"textField.text = %@",textField.text);
        NSLog(@"targetString = %@",targetString);
        return [self MatchStringFormat:targetString MatchFormat:@"^[0-9.]$"];
    }];
    
    textField.text = [self restrictMaxLength: filterText];
}

@end
